package com.day.newcorp;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CCPCookiesFormatter implements CookiesFormatter {
	private static final Logger LOG = LoggerFactory.getLogger(CCPCookiesFormatter.class);
	protected static final String COOKIE_VALUE_SPLITTER = "\\|";
	protected static final String COOKIE_VALUE_SEPARATOR = "|";
	private HttpServletRequest request = null;
	private String cookieIdentifier = null;
	private String loginToken = null;	
	private String ccpSessionId = null;
	private String lastAccessTimeStamp = null;
	
	
	public CCPCookiesFormatter(HttpServletRequest request, String cookieIdentifier) {
		this.request = request;
		this.cookieIdentifier = cookieIdentifier;
	}

	public boolean formatCookies() {
		String cookieValue = getCookie();		
		LOG.info(String.format("Cookie info for Identifier: %s and value: %s" ,cookieIdentifier,cookieValue ));
		
		//Check if cookie is null (i.e. no cookie is present in the request) and fail if so		
		if(StringUtils.isBlank(cookieValue)) {
			LOG.warn(String.format("Blank Cookie for Identifier: %s" ,cookieIdentifier ));
			return false;
		}
		
		// split the cookie into 3 main sections
		String authPieces[] = cookieValue.split(COOKIE_VALUE_SPLITTER);
		if(ArrayUtils.isEmpty(authPieces)) {
			LOG.warn(String.format("Invalid Cookie [Cookie Identifier: %s, Cookie: %s, " +"Cookie Length]", cookieValue, authPieces, ArrayUtils.getLength(authPieces)));
			return false;
		}
		
		if(!isValidUUID(authPieces[0])) {
			LOG.warn(String.format("Invalid value for Cookie [Cookie Identifier: %s, Cookie: %s, " +"Cookie Length]", cookieValue, authPieces, ArrayUtils.getLength(authPieces)));
			return false;
		}

		// Extract the CCP sessionID , token and username so that we can match it with MD5 digested value
		ccpSessionId = authPieces[0];
		
		
		if(authPieces.length == 3) {			
			loginToken = authPieces[1];	
			lastAccessTimeStamp = authPieces[2];
		}
		
		return true;
	}
	
	public String getCookie() {
		final Cookie[] cookies = request.getCookies();
		List<Cookie> ccpCookies= new ArrayList<Cookie>(); 
		try{
		if (cookies != null) {
			for (int j = 0; j < cookies.length; j++) {
				if (StringUtils.equalsIgnoreCase(cookies[j].getName(), cookieIdentifier)) {
					LOG.info("found cookie"+cookies[j].toString());
					//return new String(Base64.decodeBase64(cookies[j].getValue().getBytes("UTF-8")));
					//return cookies[j].getValue();
					ccpCookies.add(cookies[j]);
				}
			}
		}
		
		for(Cookie ccpCookie: ccpCookies) {			
			String authPieces[] = ccpCookie.getValue().split(COOKIE_VALUE_SPLITTER);			
			if(null!= authPieces && authPieces.length==3) {				
				return ccpCookie.getValue();
			}
		}
		if(ccpCookies.size() > 0){
			return ccpCookies.get(0).getValue();
		}
	
		}catch (Exception e) {
			// should NOT happen - this is supported encoding
			LOG.error("CCPCookiesFormatter getCookie: error with encoding algorithm", e);
		} 
		return null;
	}
	
	public String getCookieIdentifier() {
		return cookieIdentifier;
	}

	public String getLoginToken() {
		return loginToken;
	}

	

	
	public String getCcpSessionId() {
		return ccpSessionId;
	}

	public void setCcpSessionId(String ccpSessionId) {
		this.ccpSessionId = ccpSessionId;
	}
	
	
	
	public String getLastAccessTimeStamp() {
		return lastAccessTimeStamp;
	}

	public void setLastAccessTimeStamp(String lastAccessTimeStamp) {
		this.lastAccessTimeStamp = lastAccessTimeStamp;
	}

	private boolean isValidUUID(String uuid) {
		return uuid.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
	}
	
}
